<template>
  <!--面包屑导航-->
  <el-row style="margin: 5px 5px;">
    <el-col :span="24">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>主数据</el-breadcrumb-item>
        <el-breadcrumb-item>计量单位</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>

  <!--查询条件区-->
  <el-row>
    <el-col :span="24">
      <el-form :model="searchUnit" inline>
        <el-form-item label="单位编码">
          <el-input v-model="searchUnit.unitCode" placeholder="请输入单位编码" />
        </el-form-item>
        <el-form-item label="单位名称">
          <el-input v-model="searchUnit.unitName" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item>
          <el-button @click="fetchUnitList(searchUnit)" type="primary">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
  <!--按钮功能区-->
  <el-row style="margin: 5px 5px;">
    <el-col :span="24">
      <el-button-group>
        <el-button @click="insert" type="primary">
          新增
        </el-button>
        <el-button @click="updateTool" type="success" :disabled="selectedUnits.length > 1">
          修改
        </el-button>
        <el-button @click="deleteDevList" type="danger" :disabled="selectedUnits.length === 0">
          删除
        </el-button>
      </el-button-group>
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="24">
      <el-table :data="pagedData" border stripe style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="unitCode" label="单位编码" width="150"></el-table-column>
        <el-table-column prop="unitName" label="单位名称" width="150"></el-table-column>
        <el-table-column prop="isMainUnit" label="是否是主单位" width="120">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isMainUnit == 1">是</el-tag>
            <el-tag type="danger" v-else-if="scope.row.isMainUnit == 0">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="proportionWithMain" label="与主单位的换算" width="150"></el-table-column>
        <el-table-column prop="enableFlag" label="是否启用" width="120">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enableFlag == 1">是</el-tag>
            <el-tag type="danger" v-else-if="scope.row.enableFlag == 0">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unitRemark" label="备注" width="150"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          style="margin-top: 20px"
          background
          layout="prev, pager, next, total"
          :total="total"
          :page-size="pageSize"
          @current-change="handlePageChange"
      />
    </el-col>
  </el-row>

    <!-- 新增单位的对话框 -->
    <el-dialog title="新增单位" v-model="dialogInsertVisible">
      <el-form :model="formData" label-width="160px">
        <el-form-item label="单位编码">
          <el-input v-model="formData.unitCode"></el-input>
        </el-form-item>
        <el-form-item label="单位名称">
          <el-input v-model="formData.unitName"></el-input>
        </el-form-item>
        <el-form-item label="是否主单位">
          <el-radio-group v-model="formData.isMainUnit">
            <el-radio :value=1 label="是"/>
            <el-radio :value=0 label="否"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="主单位" prop="parentUnitId" v-if="formData.isMainUnit == 0">
          <el-select v-model="formData.parentUnitId" placeholder="请选择主单位" clearable>
            <el-option
                v-for="unit in parentUnits"
                :key="unit.unitId"
                :label="unit.unitName"
                :value="unit.unitId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="与主单位的换算比例" prop="proportionWithMain" v-if="formData.isMainUnit == 0">
          <el-input-number v-model="formData.proportionWithMain" placeholder="与主单位的换算比例"></el-input-number>
        </el-form-item>
        <el-form-item label="是否启用" v-model="formData.enableFlag" >
          <el-radio-group v-model="formData.enableFlag">
            <el-radio :value = 1 label="是"/>
            <el-radio :value = 0 label="否"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.unitRemark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogInsertVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
<!--  修改单位的弹窗-->
    <el-dialog title="修改单位" v-model="dialogUpdateVisible" >
      <el-form :model="formData" label-width="160px">
        <el-form-item label="单位编码">
          <el-input v-model="formData.unitCode"></el-input>
        </el-form-item>
        <el-form-item label="单位名称">
          <el-input v-model="formData.unitName"></el-input>
        </el-form-item>
        <el-form-item label="是否主单位">
          <el-radio-group v-model="formData.isMainUnit">
            <el-radio :value=1 label="是"/>
            <el-radio :value=0 label="否"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="主单位" prop="parentUnitId" v-if="formData.isMainUnit == 0">
          <el-select v-model="formData.parentUnitId" placeholder="请选择主单位" clearable>
            <el-option
                v-for="unit in parentUnits"
                :key="unit.unitId"
                :label="unit.unitName"
                :value="unit.unitId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="与主单位的换算比例" prop="proportionWithMain" v-if="formData.isMainUnit == 0">
          <el-input-number v-model="formData.proportionWithMain" placeholder="与主单位的换算比例"></el-input-number>
        </el-form-item>
        <el-form-item label="是否启用" v-model="formData.enableFlag" >
          <el-radio-group v-model="formData.enableFlag">
            <el-radio :value = 1 label="是"/>
            <el-radio :value = 0 label="否"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.unitRemark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogInsertVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdateForm">确定</el-button>
      </div>
  </el-dialog>
</template>

<script setup>
// 引入必要的模块
import { ref, onMounted } from 'vue';
import unitRequest from "@/api/md/unit/unit.js";
import { fetchUnitList, handlePageChange, resetSearch, pagedData, total, pageSize, searchUnit } from '@/api/md/unit/unitLogic.js';
import {ElMessage, ElMessageBox} from "element-plus";

//初始化insertForm
const formData = ref({
  unitCode: '',
  unitName: '',
  isMainUnit: '',
  enableFlag: '',
  unitRemark: '',
  parentUnitName: '',
  proportionWithMain: '',
  parentUnit: '',
  unitStatus: 1
});
//新增弹窗
const dialogInsertVisible = ref(false);
const dialogUpdateVisible = ref(false);
const parentUnits = ref([]);  // 主单位列表
// 定义查询结果和查询条件
const unitList = ref([]); // 存储单位列表数据
const editUnit = ref({});
// 存储选中的行
const selectedUnits = ref([]);
// 处理表格行选择事件
function handleSelectionChange(val) {
  selectedUnits.value = val;
}

// 批量删除操作
function deleteDevList() {
  if (selectedUnits.value.length === 0) {
    return;
  }
//弹出确认窗口
  ElMessageBox.confirm('确定要删除选中的单位吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户点击了确定按钮，执行删除操作
    unitRequest.deleteUnits(selectedUnits.value, (data) => {
      console.log(selectedUnits.value)
      if (data.msg == "OK"){
        ElMessage({
          type: "success",
          message: "删除成功"
        });
       // 重新加载数据
      }
    })
  })
}

// 初始化获取数据
fetchUnitList(searchUnit.value);
function handleEdit(row) {
  // 查询主单位的数据
  unitRequest.loadMainUnitList((data) => {
    // 转换后端返回的数据为 label 和 value 格式
    parentUnits.value = data.data.map(unit => ({
      unitId: unit.unitId,       // 存储 unitId
      unitName: unit.unitName,   // 显示 unitName
    }));
  });
  console.log(row.unitId)
  unitRequest.loadUpdateInfo(row.unitId, (data) => {
    formData.value = data.data;
    dialogUpdateVisible.value = true;
  })
}

//点击单个删除按钮后的处理函数
function handleDelete(row) {
//弹出确认窗口
  ElMessageBox.confirm('确定要删除该单位吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户点击了确定按钮，执行删除操作
    unitRequest.deleteUnit(row.unitId, (data) => {
      if (data.msg == "OK"){
        ElMessage({
          type: "success",
          message: "删除成功"
        })
        fetchUnitList(searchUnit);
      }
    })
  })
}

// 新增按钮触发事件
function insert() {
  // 查询主单位的数据
  unitRequest.loadMainUnitList((data) => {
    // 转换后端返回的数据为 label 和 value 格式
    parentUnits.value = data.data.map(unit => ({
      unitId: unit.unitId,       // 存储 unitId
      unitName: unit.unitName,   // 显示 unitName
    }));
    dialogInsertVisible.value = true;
  });
}
// 表单提交
function submitForm() {
  formData.value.parentUnitName = parentUnits.value.find(unit => unit.unitId === formData.value.parentUnitId)?.unitName;
  // 校验并提交 formData
  console.log('提交的表单数据：', formData.value);
  // 这里可以调用后端保存接口
  unitRequest.addUnit(formData.value, (data)=>{
    console.log(data)
    if (data.msg == "OK"){
      ElMessage({
        type: "success",
        message: "添加成功"
      })
      dialogInsertVisible.value = false;
    } else {
      ElMessage({
        type: "error",
        message: "添加失败"
      })
    }
  })
}

function submitUpdateForm() {
  formData.value.parentUnitName = parentUnits.value.find(unit => unit.unitId === formData.value.parentUnitId)?.unitName;
  console.log('提交的表单数据：', formData)
  unitRequest.EditDateSubmit(formData.value, (data)=>{
    if (data.msg == "OK"){
      ElMessage({
        type: "success",
        message: "修改成功"
      })
      dialogUpdateVisible.value = false;
      //清空表单

    } else {
      ElMessage({
        type: "error",
        message: "修改失败"
      })
    }
  })
}
onMounted(() => {
  fetchUnitList(searchUnit.value);  // 页面加载时获取数据

});
</script>
